<?php

namespace app\common\model;

use app\common\library\MemberVo;
use app\common\library\ModelHandle;
use think\Env;
use think\Loader;
use think\Model;

class ApiLog extends Model
{


    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    // 追加属性
    protected $append = [
    ];



    /**
     * 记录日志
     * @param string $title
     * @param string $content
     */
    public static function record($response)
    {
        $member_id = MemberVo::instance()->getMemberId();
        $content = request()->param('', null, 'trim,strip_tags,htmlspecialchars');
        $content = self::getPureContent($content);
        self::create([
            'http_code' => $response->getCode(),
            'code' => $response->getdata()['code'],
            'api'     => request()->path(),
            'method'     => request()->method(),
            'content'   => !is_scalar($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content,
            'url'       => substr(request()->url(), 0, 1500),
            'member_id'  => $member_id,
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip'        => request()->ip()
        ]);

    }

    /**
     * 获取已屏蔽关键信息的数据
     * @param $content
     * @return false|string
     */
    protected static function getPureContent($content)
    {
        if (!is_array($content)) {
            return $content;
        }
        foreach ($content as $index => &$item) {
            if (preg_match("/(password|salt|token)/i", $index)) {
                $item = "***";
            } else {
                if (is_array($item)) {
                    $item = self::getPureContent($item);
                }
            }
        }
        return $content;
    }
}
